package com.jintian.smart.platform.system.service;

import com.jintian.smart.base.api.system.entity.DictDataEntity;
import com.jintian.smart.base.api.system.entity.DictEntity;
import com.jintian.smart.base.api.system.form.*;
import com.jintian.smart.kernel.core.system.DictDataVO;
import com.jintian.smart.base.api.system.view.DictVO;
import com.jintian.smart.kernel.common.util.SmartBeanUtil;
import com.jintian.smart.kernel.common.util.SmartStringUtil;
import com.jintian.smart.kernel.core.constant.CacheKeyConst;
import com.jintian.smart.kernel.core.domain.ResponseDTO;
import com.jintian.smart.kernel.core.system.IDictService;
import com.jintian.smart.kernel.orm.impl.AbstractEntityServiceImpl;
import com.jintian.smart.platform.system.mapper.DictDataMapper;
import com.jintian.smart.platform.system.mapper.DictMapper;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.beetl.sql.core.page.PageResult;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据字典 Service
 */
@Service
public class DictService extends AbstractEntityServiceImpl<DictMapper, DictEntity> implements IDictService {
    @Resource
    private DictDataMapper dictDataMapper;

    @Resource
    private DictDataService dictDataService;

    @Resource
    private CacheManager cacheManager;

    /**
     * 获取全部数据
     */
    public List<DictDataVO> getAll() {
        return dictDataService.getEntityMapper().getAll();
    }

    /**
     * 获取所有字典
     */
    public List<DictVO> getAllDict() {

        List<DictEntity> dictEntityList = this.list().stream().filter(e -> e.getDisabledFlag() == 0).collect(Collectors.toList());
        return SmartBeanUtil.copyList(dictEntityList, DictVO.class);
    }

    /**
     * 分页查询
     */
    public PageResult<DictVO> queryPage(DictQueryForm queryForm) {
        PageResult<DictVO> pageResult = this.getEntityMapper().queryPage(queryForm);
        return pageResult;
    }

    /**
     * 添加
     */
    public synchronized ResponseDTO<String> add(DictAddForm addForm) {
        DictEntity existDictCode = this.getEntityMapper().selectByCode(addForm.getDictCode());
        if (null != existDictCode) {
            return ResponseDTO.userErrorParam("数据字典编码已经存在！");
        }

        DictEntity dictEntity = SmartBeanUtil.copy(addForm, DictEntity.class);
        this.getEntityMapper().insert(dictEntity);
        return ResponseDTO.ok();
    }

    /**
     * 禁用  启用
     */
    public ResponseDTO<String> updateDisabled(Long dictId) {
        DictEntity dictEntity = this.getById(dictId);
        if (dictEntity == null) {
            return ResponseDTO.userErrorParam("数据不存在");
        }

        dictEntity.setDisabledFlag(dictEntity.getDisabledFlag() == 0 ? 1 : 0);
        this.getEntityMapper().updateById(dictEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     */
    @CacheEvict(CacheKeyConst.Dict.DICT_DATA)
    public synchronized ResponseDTO<String> update(DictUpdateForm updateForm) {
        DictEntity existDictCode = this.getEntityMapper().selectByCode(updateForm.getDictCode());
        if (null != existDictCode && !existDictCode.getDictId().equals(updateForm.getDictId())) {
            return ResponseDTO.userErrorParam("数据字典编码已经存在！");
        }

        DictEntity dictEntity = SmartBeanUtil.copy(updateForm, DictEntity.class);
        this.getEntityMapper().updateById(dictEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    @CacheEvict(CacheKeyConst.Dict.DICT_DATA)
    public synchronized ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return ResponseDTO.ok();
        }

        this.deleteByIds(idList);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    @CacheEvict(CacheKeyConst.Dict.DICT_DATA)
    public synchronized ResponseDTO<String> delete(Long dictId) {
        if (null == dictId) {
            return ResponseDTO.ok();
        }

        this.getEntityMapper().deleteById(dictId);
        return ResponseDTO.ok();
    }


    // -------------- 字典数据 --------------------

    /**
     * 分页查询
     */
    public List<DictDataVO> queryDictData(Long dictId) {
        return dictDataMapper.queryByDictId(dictId);
    }

    /**
     * 获取字典Label
     */
    public String getDictDataLabel(String dictCode, String dataValue) {
        DictDataVO dictData = getDictData(dictCode, dataValue);
        return dictData == null ? "" : dictData.getDataLabel();
    }

    /**
     * 添加
     */
    public synchronized ResponseDTO<String> addDictData(DictDataAddForm addForm) {

        addForm.setDataValue(SmartStringUtil.trim(addForm.getDataValue()));

        DictEntity dictEntity = this.getById(addForm.getDictId());
        if (null == dictEntity) {
            return ResponseDTO.userErrorParam("数据字典不存在");
        }

        DictDataEntity existData = dictDataMapper.selectByDictIdAndValue(addForm.getDictId(), addForm.getDataValue());
        if (null != existData) {
            return ResponseDTO.userErrorParam("已存在相同value的数据");
        }

        DictDataEntity dictDataEntity = SmartBeanUtil.copy(addForm, DictDataEntity.class);
        dictDataService.save(dictDataEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     */
    @CacheEvict(value = CacheKeyConst.Dict.DICT_DATA, key = "#updateForm.dictCode + '_' + #updateForm.dataValue")
    public synchronized ResponseDTO<String> updateDictData(DictDataUpdateForm updateForm) {

        updateForm.setDataValue(SmartStringUtil.trim(updateForm.getDataValue()));

        DictEntity dictEntity = this.getById(updateForm.getDictId());
        if (null == dictEntity) {
            return ResponseDTO.userErrorParam("数据字典不存在");
        }

        DictDataEntity existData = dictDataMapper.selectByDictIdAndValue(updateForm.getDictId(), updateForm.getDataValue());
        if (null != existData && !existData.getDictDataId().equals(updateForm.getDictDataId())) {
            return ResponseDTO.userErrorParam("已存在相同value的数据");
        }

        DictDataEntity dictDataEntity = SmartBeanUtil.copy(updateForm, DictDataEntity.class);
        dictDataService.updateById(dictDataEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public synchronized ResponseDTO<String> batchDeleteDictData(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return ResponseDTO.ok();
        }
        // 清除缓存
        clearDictDataCache(idList);
        // 删除
        dictDataService.deleteByIds(idList);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public synchronized ResponseDTO<String> deleteDictData(Long dictDataId) {
        if (null == dictDataId) {
            return ResponseDTO.ok();
        }
        // 清除缓存
        clearDictDataCache(Collections.singletonList(dictDataId));
        // 删除
        dictDataService.deleteById(dictDataId);
        return ResponseDTO.ok();
    }


    /**
     * 清空字典数据缓存
     */
    private void clearDictDataCache(List<Long> idList) {
        List<DictDataVO> dictDataList = dictDataMapper.selectByDictDataIds(idList);
        Cache cache = cacheManager.getCache(CacheKeyConst.Dict.DICT_DATA);
        if (cache == null) {
            return;
        }

        for (DictDataVO dictDataVO : dictDataList) {
            cache.evict(dictDataVO.getDictCode() + "_" + dictDataVO.getDataValue());
        }
    }


    /**
     * 更新启用/禁用
     */
    public synchronized ResponseDTO<String> updateDictDataDisabled(Long dictDataId) {
        DictDataEntity dictDataEntity = dictDataService.getById(dictDataId);
        if (dictDataEntity == null) {
            return ResponseDTO.userErrorParam("数据不存在");
        }

        dictDataEntity.setDisabledFlag(dictDataEntity.getDisabledFlag() == 0 ? 1 : 0);
        dictDataService.updateById(dictDataEntity);
        return ResponseDTO.ok();
    }

    /**
     * 获取字典
     */
    @Cacheable(value = CacheKeyConst.Dict.DICT_DATA, key = "#dictCode + '_' + #dataValue")
    public DictDataVO getDictData(String dictCode, String dataValue) {
        DictEntity dictEntity = this.getEntityMapper().selectByCode(dictCode);
        if (dictEntity == null) {
            return null;
        }

        DictDataEntity dictDataEntity = dictDataMapper.selectByDictIdAndValue(dictEntity.getDictId(), dataValue);
        return SmartBeanUtil.copy(dictDataEntity, DictDataVO.class);
    }
}
